package lime2;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;

import sagroup.util.Lights;
import sagroup.util.Limes;

import static org.junit.Assert.*;
import lights.dracots.Field;
import lights.dracots.Tuple;
import lights.interfaces.IValuedField;

/**
 * You should not call <code>server.shutdown()</code>. Just leave the task of
 * releasing system resources to JVM when the process ends. <br>
 * 
 * @author Wenhui Pan
 * 
 */
public abstract class LimeTestCase extends TestCase{

	protected static Logger logger = Logger.getLogger("com.wombat.nose");
	protected LimeTupleSpace lts;
	protected List<ReactionID> lrs = new LinkedList<ReactionID>();

	
	public LimeTestCase() {
		super();
	}

	public LimeTestCase(String name) {
		super(name);
		Limes.startServer(1973, 8973);
	}

	@Before
	protected void setUp() throws Exception {
		
		lts = LimeTupleSpace.get("share");
		helpTestReaction(new int[] { 0, 0 }, lts);
	}

	@After
	protected void tearDown() throws Exception {
		/* in all tuples and remove all reactions of here. */
		lts.removeStrongReaction(lrs.toArray(new ReactionID[0]));
		lts.ing(Limes.createHUTemplate(Field.MATCH_ALL_FIELD.getValue()));
		helpTestReaction(new int[] { 0, 0 }, lts);
	}

	protected void out(Object i) {
		lts.out(Lights.creatTuple(i));
	}

	protected void out(Location l, Object i) {
		lts.out(l, Lights.creatTuple(i));
	}

	private void helpTestReaction(int[] expected, LimeTupleSpace lts) {
		assertEquals(2, expected.length);
		assertEquals("totalTuples is not right!", expected[0], lts.rdg(Limes
				.createHHTemplate(null)).length);
		assertEquals("totalReaction is not right!", expected[1], lts
				.getTextualRegisteredReactions().length);
	}

	protected class CountAndDispReactionListener implements ReactionListener {
		int totalReadctedTuple = 0;

		public int getTotalReactedTuple() {
			return totalReadctedTuple;
		}

		public void reactsToOut(ReactionEvent re) {
			logger.info("reaction fires on [" + re.getLimeTuple() + "] ");
			totalReadctedTuple++;
		}

		public void reactsToTake(ReactionEvent re) {
			// TODO Auto-generated method stub

		}
	}
}